package com.zwp.base.di

import android.util.Log
import com.zwp.base.constant.NetConstant
import com.zwp.base.repository.LocalCookie
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object NetModule {

    @Singleton
    @Provides
    fun providerOkHttpClient() =
        OkHttpClient.Builder()
            .connectTimeout(NetConstant.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(NetConstant.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(NetConstant.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .addInterceptor(OkhttpLogger)
//            .cookieJar(LocalCookie())
            .build()

    @Singleton
    @Provides
    fun providerRetrofit(okHttpClient: OkHttpClient) =
        Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(NetConstant.BASE_URL)
            .client(okHttpClient)
            .build()


    private object OkhttpLogger : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            Log.d("OkhttpLogger", "raw request：${request}")
            val response = chain.proceed(request)
            Log.d("OkhttpLogger", "raw response：${response.peekBody(1024 * 10).string()}")
            return response
        }
    }
}